package org.example.demo.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
        // 获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        // 获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/1.jpg");
        // 创建输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        // 创建字节数组
        byte[] bytes = new byte[inputStream.available()];
        // 将流读取到字节数组中
        inputStream.read(bytes);
        // 创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        // 设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment:filename=1.jpg");
        // 设置响应状态码
        HttpStatus httpStatus = HttpStatus.OK;
        // 创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, httpStatus);
        // 关闭输入流
        inputStream.close();
        return responseEntity;
    }

    // 需要配置文件上传解析器，将上传的文件封装为MultipartFile对象
    @PostMapping("/upload")
    public String upload(MultipartFile avatar, HttpSession session) throws IOException {
        System.out.println(avatar.getName());
        System.out.println(avatar.getOriginalFilename());

        String originalFilename = avatar.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 将uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        originalFilename = uuid + suffixName;

        ServletContext servletContext = session.getServletContext();
        // 获取服务器中avatar存放的文件夹位置
        String realPath = servletContext.getRealPath("img");
        File file = new File(realPath);
        // 判断realPath是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        String finalPath = realPath + File.separator + originalFilename;

        avatar.transferTo(new File(finalPath));
        return "success";
    }
}
